package com.happy.services;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import com.happy.entity.Authority;
import com.happy.entity.Roles;
import com.happy.entity.User;

public class LoginValidate implements UserDetailsService {

	@Autowired
	private UserServices services;

	public UserDetails loadUserByUsername(String arg0)
			throws UsernameNotFoundException, DataAccessException {
		// TODO Auto-generated method stub
		User user = services.getUserByName(arg0);
		if (user==null) {
			 throw new UsernameNotFoundException("用户名或者密码错误");
		}
//		Set<Roles> a=user.getRole();
//		Iterator<Roles> ab=a.iterator();
//		while(ab.hasNext())
//		{
//			System.out.println(ab.next().getRoleName());
//		}
		List<GrantedAuthority> authsList = new ArrayList<GrantedAuthority>();
		for (Roles roles : user.getRole()) {
			for (Authority au : roles.getAuthority()) {
				authsList.add(new GrantedAuthorityImpl(au.getAuthorityName()));
			}
		}
		org.springframework.security.userdetails.User userdetail = new org.springframework.security.userdetails.User(
				user.getUserName(),user.getUserPassword(), true, true, true,
				true, authsList.toArray(new GrantedAuthority[authsList.size()]));

		return userdetail;
	}

}
